<template>
  <el-dialog v-bind="dialogProps" :before-close="handleClose" :close-on-click-modal="false" :destroy-on-close="true"
             v-dialogDrag>
    <el-form ref="form" :rules="rules" :model="formEvent" label-width="120px" :size="size">
      <el-row :gutter="16">
        <!-- 通过调整lg的大�?  12 24/3=12 会变为一�?3�? -->
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
          <el-form-item label="巡视名称" prop="taskName">
            <el-input v-model="formEvent.taskName" placeholder="会自动生成,请填写其他选项" clearable type="textarea"
                      :rows="1"
                      :autosize="{ minRows: 1, maxRows: 5 }" @input="getTaskName" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item label="单位名称" prop="maintainUnitNo">
            <el-select v-model="formEvent.maintainUnitNo" placeholder="请选择单位" clearable @change="deptNoChange"
                       disabled>
              <el-option v-for="item in OptionData.OptionData_deptNo" :key="item.value" :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
          <el-form-item label="巡视对象名称" prop="patrolTargetNames">
            <el-input v-model="formEvent.patrolTargetNames" placeholder="无数据" disabled>
              <el-checkbox slot="append" v-model="formEvent.equipAllSelect" :true-label="1" :false-label="0" disabled>
                全机房
              </el-checkbox>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item label="能源站名称" prop="patrolRoomName">
            <el-input v-model="formEvent.patrolRoomName" placeholder="无数据" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item label="巡视类型" prop="patrolTypeNo">
            <el-select v-model="formEvent.patrolTypeNo" placeholder="请选择巡视类型" clearable
                       @change="taskTypeNoChange"
                       disabled>
              <el-option v-for="item in OptionData.OptionData_taskTypeNo" :key="item.value" :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="periodShow" :xs="24" :sm="8" :md="8" :lg="12" :xl="8">
          <el-form-item label="巡视周期" prop="period">
            <el-input v-if="formEvent.patrolTypeNo == '1'" v-model="formEvent.period" placeholder="请输入周期"
                      disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col v-if="periodShow" :xs="24" :sm="8" :md="8" :lg="12" :xl="8">
          <el-form-item label="周期结束时间" prop="periodEndTime">
            <el-date-picker v-model="formEvent.periodEndTime" type="datetime" style="width:100%" placeholder="年/月/日"
                            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" disabled>
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item label="计划开始时间" prop="planStartTime">
            <el-date-picker v-model="formEvent.planStartTime" type="datetime" style="width:100%"
                            placeholder="请选择计划开始时间"
                            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" disabled>
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item label="计划结束时间" prop="planEndTime">
            <el-date-picker v-model="formEvent.planEndTime" type="datetime" style="width:100%"
                            placeholder="请选择计划结束时间"
                            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" disabled>
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="巡视内容" prop="patrolDescription">
            <el-input v-model="formEvent.patrolDescription" placeholder="请填写巡视内容" clearable type="textarea"
                      disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="备注">
            <el-input v-model="formEvent.remark" placeholder="请填写巡视内容" clearable type="textarea" disabled>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 主键是不可以编辑的，不可查看�? -->
      <el-input v-model="formEvent.id" v-show="false"></el-input>
      <div>
        <h3 style="color:#009688;">巡视设备列表</h3>
      </div>
      <div style="width:100%;height:2px;background:#009688;margin-bottom: 10px;"></div>
      <vxe-table border stripe ref="selectedEquip" height="300" :data="list.data">
        <vxe-column type="seq" title="序号" width="60" align="center"></vxe-column>
        <vxe-column field="equipName" title="单位" align="center" minWidth="150"></vxe-column>
        <vxe-column field="equipName" title="班组" align="center" minWidth="150"></vxe-column>
        <vxe-column field="ccbm" title="出厂编码" align="center" minWidth="150"></vxe-column>
        <vxe-column field="equipName" title="设备名称" align="center" minWidth="150"></vxe-column>
        <vxe-column field="equipTypeName" title="设备类型" align="center" minWidth="150"></vxe-column>
      </vxe-table>
      <div>
        <h3 style="color:#009688;">派单信息</h3>
      </div>
      <div style="width:100%;height:2px;background:#009688;margin-bottom: 10px;"></div>
      <el-row>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item label="派单人" prop="sendPersonName">
            <el-input v-model="formEvent.sendPersonName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item label="派单人电话" prop="sendTel">
            <el-input v-model="formEvent.sendTel"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item label="派单时间" prop="sendTime">
            <el-date-picker v-model="formEvent.sendTime" type="datetime" style="width:100%" disabled
                            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
        </el-col>

      </el-row>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCancel()" size="medium" icon="fa fa-minus-square-o">取消</el-button>
      <el-button type="primary" @click="handleSubmit()" size="medium" icon="fa fa-save (alias)">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {FormEvent} from "../model/workOrderManagement-form.js";
import {reactive} from "vue";
import {workOrderManagement} from '@/api/patrol/workOrderManagement.js'
import {CommonApi} from '@/api/equip/CommonApi.js'
import {getInfo} from "@/api/login";
import {listDept} from "@/api/system/dept";
import moment from "moment";

export default {
  components: {},
  name: "preparationTaskForm",
  props: {
    formData: {
      type: Object,
    },
  },
  data() {
    return {
      dialogProps: {
        visible: false,
        title: "巡视工单派发",
        width: "70%",
        top: "5px",
      },
      size: "small",
      formEvent: reactive(FormEvent).form,
      // rules: reactive(FormEvent).rules,
      periodShow: false,
      taskNoShow: false,
      OptionData: {
        OptionData_warehouseNo: [],
        OptionData_stockType: [],
        OptionData_deptNo: [],
        OptionData_teamNo: [],
        OptionData_taskTypeNo: [],
        OptionData_personNo: [{label: 'zyn', value: '1111'}],
      },
      list: {
        data: [],
        pageNo: 1,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        total: 0,
      },
      pagerShow: false,
      isEdit: false,
      isDisabled: false,
      row: {},
      xqbzData: [],


    };
  },
  watch: {

    'formEvent.deptNo'(val) {
      if (val !== '') {
        if (!this.isEdit) { //编辑情况下，不做修改
          this.setTestTaskName()
        }
      }

    },
    'formEvent.warehouseNo'(val) {
      if (val !== '') {
        if (!this.isEdit) { //编辑情况下，不做修改
          this.setTestTaskName()
        }
      }
    },
    'formEvent.taskTypeNo'(val) {
      if (val !== '') {
        if (!this.isEdit) { //编辑情况下，不做修改
          this.setTestTaskName()
        }
      }
    },

  },
  computed: {
    rules() {
      const obj = {
        sendTel: ""
      }
      const fields = Object.keys(obj)
      const rules = {}
      fields.forEach(d => {
        rules[d] = [
          {required: true, message: '派单人电话不能为空',}
        ]
      })
      rules.sendTel = [
        {required: true, message: '派单人电话不能为空'},
        {validator: this.validationPart1, trigger: ['blur', 'change']}

      ]

      return rules

    }
  },
  mounted() {

  },
  methods: {
    validationPart1(rule, value, callback) {
      let moblie = /^1(3|4|5|6|7|8|9)\d{9}$/
      let tel = /^(0[0-9]{2,3}\-)([2-9][0-9]{4,7})+(\-[0-9]{1,4})?$/
      if (moblie.test(this.formEvent.sendTel) || tel.test(this.formEvent.sendTel)) {
        callback()
      } else {
        callback(new Error('请输入正确合规的手机号码或者座机号码(区号-座机号码)'))
      }
    },
    validationPart2(rule, value, callback) {
      if (this.formEvent.planStime < this.formEvent.planEtime) {
        callback()
      } else {
        callback(new Error('结束时间必须大于开始时间'))
      }
    },
    validationSpace(rule, value, callback) {
      if (this.formEvent.description.trim().length !== 0) {
        callback()
      } else {
        callback(new Error('不能输入空格'))
      }
    },
    showDialog(isEdit, row, isDisabled) {
      this.isEdit = isEdit || false
      this.isDisabled = isDisabled || false
      this.row = row.row || {}
      this.getOptionData_gldw()
      this.getOptionData_team()
      this.getOptionData_taskTypeNo()
      this.dialogProps.visible = true
      if (isEdit) {
        this.initData()
      }
    },
    getOptionData_gldw() {//获取管理单位：字典表
      getInfo().then(res => {
        let params = {
          deptId: res.user.dept.deptId,
          parentId: res.user.dept.parentId
        }
        listDept(params).then(res => {
          // 修改编辑框
          // const sexColumn = $grid.getColumnByField('sex')
          // sexColumn.editRender.options = sexList
          // 修改查询条件列表
          let optionList = [
            {label: '请选择', value: ''}
          ]
          res.data.forEach((item) => {
            // console.log(item,'item.,,,');
            optionList.push({label: item.deptName, value: item.deptId})
          })
          this.OptionData.OptionData_deptNo = optionList;
        })
      })
    },
    getOptionData_team() {
      var obj = {
        deptId: "",
        parentId: this.row.maintainUnitNo,
      }
      listDept(obj).then(res => {
        // 修改编辑框
        // const sexColumn = $grid.getColumnByField('sex')
        // sexColumn.editRender.options = sexList
        // 修改查询条件列表
        let optionList = [
          {label: '请选择', value: ''}
        ]
        res.data.forEach((item) => {
          // console.log(item,'item.,,,');
          optionList.push({label: item.deptName, value: item.deptId})
        })
        this.OptionData.OptionData_teamNo = optionList;
      })
    },
    getOptionData_taskTypeNo() {//获取任务类型：字典表
      CommonApi.queryDictData('EN_PATROL_TASK_TYPE').then(res => {
        let optionList = [
          {label: '', value: ''}
        ]
        res.data.forEach((item) => {
          optionList.push({label: item.value, value: item.code})
        })
        this.OptionData.OptionData_taskTypeNo = optionList;
      }).catch(err => {
        console.log(err)
      })
    },
    getOptionData_warehouseNo(data) {//盘点对象：字典表
      CommonApi.getKfByGldw(data).then(res => {
        let optionList = [
          {label: '', value: ''}
        ]
        res.data.forEach((item) => {
          optionList.push({label: item.value, value: item.code})
        })
        this.OptionData.OptionData_warehouseNo = optionList;
      }).catch(err => {
        console.log(err)
      })
    },
    deptNoChange(value) {
      this.formEvent.deptName = '';
      if (value) {
        let arr = this.OptionData.OptionData_deptNo.filter(item => {
          return item.value == value;
        })
        if (arr && arr.length > 0) {
          this.formEvent.deptName = arr[0].label;
        }
      }

    },
    warehouseNoChange(value) {
      this.formEvent.warehouseName = '';
      if (value) {
        let arr = this.OptionData.OptionData_warehouseNo.filter(item => {
          return item.value == value;
        })
        if (arr && arr.length > 0) {
          this.formEvent.warehouseName = arr[0].label;
        }
      }

    },
    stockTypeNoChange(value) {
      this.formEvent.stockTypeName = '';
      let arrList = []
      if (value) {
        let arr = this.OptionData.OptionData_stockType.filter(item => {
          return value.indexOf(item.value) != -1
        })
        arr.forEach(item => {
          arrList.push(item.label)
        })
        this.formEvent.stockTypeName = arrList.join(',')


      }

    },
    taskTypeNoChange(value) {
      if (value == '1') {
        this.periodShow = true

      } else {
        this.periodShow = false
        this.formEvent.period = ''
        this.formEvent.periodEtime = ''
      }
      this.formEvent.taskTypeName = '';
      if (value) {
        let arr = this.OptionData.OptionData_taskTypeNo.filter(item => {
          return item.value == value;
        })
        if (arr && arr.length > 0) {
          this.formEvent.taskTypeName = arr[0].label;
        }
      }


    },
    personNoChange(value) {
      this.formEvent.personName = '';
      if (value) {
        let arr = this.OptionData.OptionData_personNo.filter(item => {
          return item.value == value;
        })
        if (arr && arr.length > 0) {
          this.formEvent.personName = arr[0].label;
        }
      }
    },
    getTaskName(event) {
      if (event.target.value !== undefined) {
        this.formEvent.rwName = event.target.value
      } else {
        this.formEvent.rwName = ''
      }

    },

    setTestTaskName() {
      const deptNo = this.OptionData.OptionData_deptNo.find(d => d.value === this.formEvent.deptNo) ? this.OptionData.OptionData_deptNo.find(d => d.value === this.formEvent.deptNo).label : ''
      const warehouseNo = this.OptionData.OptionData_warehouseNo.find(d => d.value === this.formEvent.warehouseNo) ? this.OptionData.OptionData_warehouseNo.find(d => d.value === this.formEvent.warehouseNo).label : ''
      const taskTypeNo = this.OptionData.OptionData_taskTypeNo.find(d => d.value === this.formEvent.taskTypeNo) ? this.OptionData.OptionData_taskTypeNo.find(d => d.value === this.formEvent.taskTypeNo).label : ''
      this.formEvent.taskName = deptNo + warehouseNo + taskTypeNo + this.formEvent.rwName

    },
    getTable() {
      workOrderManagement.getTaskEquipList(this.row.taskNo).then(res => {
        this.list.data = res.data
        this.list.total = res.data.length
      }).catch(err => {

      })
    },
    onSelectEquips(data) {
      this.list.data = this.list.data.concat(data)
      let arr = []
      this.list.data.forEach(item => {
        if (!arr.filter(cell => item.sbbm == cell.sbbm).length) {
          arr.push(item)
        }
      })
      this.list.data = arr

    },
    handleDelete() {
      const rowArr = this.$refs.selectedEquip.getCheckboxRecords(true)
      this.list.data = this.list.data.filter(d => rowArr.findIndex(b => b.sbbm === d.sbbm) < 0)

    },
    initData() { 		//初始化表单信�?//
      console.log(this.row)
      for (let key in this.formEvent) {
        this.formEvent[key] = this.row[key];
      }
      this.getOptionData_warehouseNo(this.row.maintainUnitNo)
      getInfo().then(res => {
        this.formEvent.sendPersonName = res.user.nickName
        this.formEvent.sendTime = moment().format("YYYY-MM-DD HH:mm:ss")
      })
      if (this.formEvent.patrolTypeNo === '1') {
        this.periodShow = true
      } else {
        this.periodShow = false
      }
      if (this.formEvent.maintainUnitNo) {
        var obj = {
          deptId: '',
          parentId: this.formEvent.maintainUnitNo,
        }
        listDept(obj).then(res => {
          let optionList = [
            {label: '请选择', value: ''}
          ]
          res.data.forEach((item) => {
            // console.log(item,'item.,,,');
            optionList.push({label: item.deptName, value: item.deptId})
          })
          this.xqbzData = optionList
        })
      }
      this.getTable()
    },

    //确定
    handleSubmit() {


      const api = this.isEdit ? 'sendOrder' : 'insertData'
      const label = this.isEdit ? '派单' : '新增'

      this.$refs.form.validate((valid) => {
        if (valid) {
          const queryParam = Object.assign({}, this.formEvent)

          const params = {
            ...queryParam,
            taskEquipVoList: this.list.data
          }
          workOrderManagement[api](params).then(res => {
            if (res.code === '200') {
              this.$message.success(label + '成功')
              this.handleCancel()
              this.$emit('onSearch')
            }
          })

          this.handleCancel()
          this.dialogProps.visible = false;


        } else {
          return false;
        }
      });

    },
    //取消
    handleCancel() {
      this.$refs.form.resetFields()
      for (let key in this.formEvent) {
        this.formEvent[key] = "";
      }
      this.formEvent.stockType = []
      this.list = {
        data: [],
      }
      this.row = {}
      this.dialogProps.visible = false;
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.handleCancel()
          this.dialogProps.visible = false;
        })
        .catch((_) => {
        });
    },
  },
};
</script>

<style scoped>
.tool-button-container {
  text-align: right;
}

.el-select {
  width: 100% !important
}
</style>
